package org.fast.easy.messages.service.impl;

import cn.hutool.core.util.RandomUtil;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.fast.easy.core.constant.Constants;
import org.fast.easy.core.constant.GlobalConstants;
import org.fast.easy.core.domain.result.R;
import org.fast.easy.framework.mail.config.properties.MailProperties;
import org.fast.easy.framework.mail.utils.MailUtils;
import org.fast.easy.framework.redis.utils.RedisUtils;
import org.fast.easy.messages.service.IEmailService;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * 类说明
 *
 * @author YanMing
 * @date 2024/5/17
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class EmailServiceImpl implements IEmailService {
    private final MailProperties mailProperties;

    /**
     * 发送邮件验证码
     * @param email
     * @return
     */
    public R<Void> emailCode(String email) {
        if (!mailProperties.getEnabled()) {
            return R.fail("当前系统没有开启邮箱功能！");
        }
        String key = GlobalConstants.CAPTCHA_CODE_KEY + email;
        String code = RandomUtil.randomNumbers(4);
        RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
        try {
            MailUtils.sendText(email, "登录验证码", "您本次验证码为：" + code + "，有效性为" + Constants.CAPTCHA_EXPIRATION + "分钟，请尽快填写。");
        } catch (Exception e) {
            log.error("验证码短信发送异常 => {}", e.getMessage());
            return R.fail(e.getMessage());
        }
        return R.ok();
    }
}
